<?php
class WorkflowNode extends Eloquent {
	protected $table = 'workflow_node';
	public $timestamps = false;
	protected $fillable = ['name','operate','condition', 'act_order','route','display_name'];
	
	public function setWorkflow(Order $order)
	{
		if ( $this->checkWorkflow($order) ) {
			return $this->setWorkflowStep($order);
		}else{
			return false;
		}
	}
	
	public function checkWorkflow(Order $order)
	{
		if ( !empty($this->condition) ) {
			$slices = preg_split("/\s+(and|or)\s+/",$this->condition,0,PREG_SPLIT_DELIM_CAPTURE);
			$obj = Order::where('id','=',$order->id);
			for( $i=0; $i<count($slices); $i+=2 ){
				list($col,$opr,$val) = $this->parseCond($slices[$i]);
				if($i==0){
					$obj = $obj->where($col, $opr,$val);
				}else{
					$func = strtolower( $slices[$i-1] )=='or' ? 'orWhere':'where';
					$obj = $obj->$func($col, $opr, $val);
				}
			}
			return $obj->firstOrFalse() == FALSE ? FALSE : TRUE;
			
		}else{
			return TRUE;
		}
	}
	
	public function setWorkflowStep(Order $order)
	{
		if ( $this->route )
		{
			return;
		}
		if ($this->operate) {
			$operations = explode(',', $this->operate );
			foreach ($operations as $opr)
			{
				list($col, $_op, $val) = $this->parseCond( trim($opr) );
				$order->$col = $val;
			}
			return $order->save();
		}
	}
	
	public function parseCond($condstr)
	{
		$arr = preg_split("/(\=|>|<|<>)/", $condstr,0,PREG_SPLIT_DELIM_CAPTURE);
		return $arr;
	}
	
	public function get_order_state()
	{
		$ret = 0;
		if ( $this->operate ) {
			$operations = explode(',', $this->operate );
			foreach ($operations as $opr){
				list($nam,$val) = explode('=', $opr) ;
				if ($nam == 'state') {
					return $val;
				}
			}
		}
		return $ret;
	}

}